<template>
  <div class="work-logs-container">
    <el-card shadow="never" class="header-card">
      <div class="page-header">
        <div class="header-content">
          <el-icon class="header-icon" :size="28"><Notebook /></el-icon>
          <div class="header-text">
            <h2>工作日志</h2>
            <p>记录和管理每日工作</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showDialog = true">
            <el-icon><Plus /></el-icon>
            写日志
          </el-button>
        </div>
      </div>
    </el-card>

    <el-row :gutter="20">
      <!-- 左侧日历 -->
      <el-col :span="6">
        <el-card shadow="never" class="calendar-card">
          <el-calendar v-model="selectedDate" style="height: fit-content;">
            <template #date-cell="{ data }">
              <div class="calendar-day" @click="handleDateClick(data.day)">
                <div :class="['day-number', { 'has-log': hasLog(data.day), 'today': isToday(data.day) }]">
                  {{ data.day.split('-').slice(2).join('-') }}
                </div>
              </div>
            </template>
          </el-calendar>
        </el-card>

        <!-- 统计信息 -->
        <el-card shadow="never" style="margin-top: 20px;">
          <div class="stat-title">本月统计</div>
          <div class="stat-list">
            <div class="stat-item">
              <span class="stat-label">日志数</span>
              <span class="stat-value">{{ stats.monthLogs }}篇</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">完成任务</span>
              <span class="stat-value">{{ stats.completedTasks }}个</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">工作时长</span>
              <span class="stat-value">{{ stats.workHours }}小时</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧日志列表 -->
      <el-col :span="18">
        <el-card shadow="never">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="我的日志" name="my" />
            <el-tab-pane label="下属日志" name="subordinate" />
            <el-tab-pane label="部门日志" name="department" />
          </el-tabs>

          <el-timeline>
            <el-timeline-item
              v-for="log in filteredLogs"
              :key="log.id"
              :timestamp="log.date"
              placement="top"
            >
              <el-card class="log-card">
                <div class="log-header">
                  <div class="log-title">
                    <el-avatar :size="36" :src="log.avatar">{{ log.author[0] }}</el-avatar>
                    <div class="author-info">
                      <div class="author-name">{{ log.author }}</div>
                      <div class="log-date">{{ log.date }} {{ log.time }}</div>
                    </div>
                  </div>
                  <div class="log-actions">
                    <el-button link type="primary" @click="handleView(log)">
                      <el-icon><View /></el-icon>
                      查看
                    </el-button>
                    <el-button link type="success" @click="handleEdit(log)" v-if="log.author === '张三'">
                      <el-icon><Edit /></el-icon>
                      编辑
                    </el-button>
                    <el-button link type="warning" @click="handleComment(log)">
                      <el-icon><ChatDotRound /></el-icon>
                      评论
                    </el-button>
                  </div>
                </div>

                <el-divider />

                <div class="log-content">
                  <div class="content-section">
                    <div class="section-title">
                      <el-icon><CircleCheck /></el-icon>
                      今日完成
                    </div>
                    <ul class="task-list">
                      <li v-for="(task, index) in log.completedTasks" :key="index">{{ task }}</li>
                    </ul>
                  </div>

                  <div class="content-section">
                    <div class="section-title">
                      <el-icon><Clock /></el-icon>
                      明日计划
                    </div>
                    <ul class="task-list">
                      <li v-for="(task, index) in log.plannedTasks" :key="index">{{ task }}</li>
                    </ul>
                  </div>

                  <div class="content-section" v-if="log.issues">
                    <div class="section-title">
                      <el-icon><WarningFilled /></el-icon>
                      遇到问题
                    </div>
                    <p class="text-content">{{ log.issues }}</p>
                  </div>
                </div>

                <div class="log-footer">
                  <el-tag size="small">工作时长：{{ log.workHours }}小时</el-tag>
                  <el-tag size="small" type="success" v-if="log.commentCount > 0">
                    <el-icon><ChatDotRound /></el-icon>
                    {{ log.commentCount }}条评论
                  </el-tag>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>

          <el-empty v-if="filteredLogs.length === 0" description="暂无日志" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 新建/编辑日志对话框 -->
    <el-dialog v-model="showDialog" :title="dialogTitle" width="800px" destroy-on-close>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="今日完成" prop="completedTasks">
          <el-input
            v-model="completedTaskInput"
            placeholder="输入完成的任务，按回车添加"
            @keyup.enter="addCompletedTask"
          >
            <template #append>
              <el-button @click="addCompletedTask">添加</el-button>
            </template>
          </el-input>
          <div class="task-tags">
            <el-tag
              v-for="(task, index) in form.completedTasks"
              :key="index"
              closable
              @close="form.completedTasks.splice(index, 1)"
              style="margin: 4px;"
            >
              {{ task }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="明日计划" prop="plannedTasks">
          <el-input
            v-model="plannedTaskInput"
            placeholder="输入计划任务，按回车添加"
            @keyup.enter="addPlannedTask"
          >
            <template #append>
              <el-button @click="addPlannedTask">添加</el-button>
            </template>
          </el-input>
          <div class="task-tags">
            <el-tag
              v-for="(task, index) in form.plannedTasks"
              :key="index"
              closable
              @close="form.plannedTasks.splice(index, 1)"
              style="margin: 4px;"
            >
              {{ task }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="遇到问题" prop="issues">
          <el-input v-model="form.issues" type="textarea" :rows="4" placeholder="描述遇到的问题（选填）" />
        </el-form-item>
        <el-form-item label="工作时长" prop="workHours">
          <el-input-number v-model="form.workHours" :min="0" :max="24" :step="0.5" />
          <span style="margin-left: 10px;">小时</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSave">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Notebook, Plus, View, Edit, ChatDotRound, CircleCheck, Clock, WarningFilled
} from '@element-plus/icons-vue'

// 状态
const selectedDate = ref(new Date())
const activeTab = ref('my')
const completedTaskInput = ref('')
const plannedTaskInput = ref('')

// 统计数据
const stats = reactive({
  monthLogs: 18,
  completedTasks: 45,
  workHours: 156
})

// 日志数据
const logs = ref([
  {
    id: 1,
    author: '张三',
    avatar: '',
    date: '2024-01-15',
    time: '18:30',
    completedTasks: [
      '完成用户登录功能开发',
      '修复数据统计bug',
      '参加项目评审会议'
    ],
    plannedTasks: [
      '开发用户权限管理模块',
      '优化数据库查询性能'
    ],
    issues: '在测试环境发现部分接口响应较慢，需要进一步优化',
    workHours: 8.5,
    commentCount: 2
  },
  {
    id: 2,
    author: '李四',
    avatar: '',
    date: '2024-01-15',
    time: '17:45',
    completedTasks: [
      '完成产品需求文档',
      '与客户沟通需求'
    ],
    plannedTasks: [
      '整理需求变更记录',
      '准备下周评审材料'
    ],
    issues: '',
    workHours: 8,
    commentCount: 0
  },
  {
    id: 3,
    author: '张三',
    avatar: '',
    date: '2024-01-14',
    time: '18:00',
    completedTasks: [
      '代码审查',
      '技术方案讨论',
      '编写接口文档'
    ],
    plannedTasks: [
      '继续开发登录功能',
      '单元测试编写'
    ],
    issues: '',
    workHours: 8,
    commentCount: 1
  }
])

// 对话框
const showDialog = ref(false)
const formRef = ref(null)
const currentLog = ref(null)
const dialogTitle = computed(() => currentLog.value ? '编辑日志' : '写日志')

// 表单
const form = reactive({
  date: new Date(),
  completedTasks: [],
  plannedTasks: [],
  issues: '',
  workHours: 8
})

// 表单验证规则
const rules = {
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  completedTasks: [
    { 
      type: 'array', 
      required: true, 
      message: '请至少添加一项完成的任务', 
      trigger: 'change',
      min: 1
    }
  ]
}

// 计算属性
const filteredLogs = computed(() => {
  return logs.value
})

// 方法
const hasLog = (date) => {
  return logs.value.some(log => log.date === date)
}

const isToday = (date) => {
  return date === new Date().toISOString().split('T')[0]
}

const handleDateClick = (date) => {
  console.log('选择日期', date)
}

const handleView = (log) => {
  ElMessageBox.alert(
    `作者：${log.author}\n日期：${log.date}\n工作时长：${log.workHours}小时`,
    '日志详情',
    { confirmButtonText: '确定', type: 'info' }
  )
}

const handleEdit = (log) => {
  currentLog.value = log
  Object.assign(form, {
    date: log.date,
    completedTasks: [...log.completedTasks],
    plannedTasks: [...log.plannedTasks],
    issues: log.issues || '',
    workHours: log.workHours
  })
  showDialog.value = true
}

const handleComment = (log) => {
  ElMessageBox.prompt('请输入评论内容', '添加评论', {
    confirmButtonText: '发送',
    cancelButtonText: '取消',
    inputType: 'textarea'
  }).then(() => {
    log.commentCount++
    ElMessage.success('评论成功')
  }).catch(() => {})
}

const addCompletedTask = () => {
  if (completedTaskInput.value.trim()) {
    form.completedTasks.push(completedTaskInput.value.trim())
    completedTaskInput.value = ''
  }
}

const addPlannedTask = () => {
  if (plannedTaskInput.value.trim()) {
    form.plannedTasks.push(plannedTaskInput.value.trim())
    plannedTaskInput.value = ''
  }
}

const handleSave = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('提交成功')
      showDialog.value = false
      // 重置表单
      form.completedTasks = []
      form.plannedTasks = []
      form.issues = ''
      form.workHours = 8
    }
  })
}
</script>

<style scoped>
.work-logs-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  color: #409EFF;
}

.header-text h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-text p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.calendar-day {
  min-height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.day-number {
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-radius: 50%;
}

.day-number.today {
  background-color: #409EFF;
  color: white;
}

.day-number.has-log {
  font-weight: bold;
  color: #67C23A;
}

.stat-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
}

.stat-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.stat-label {
  color: #606266;
}

.stat-value {
  font-weight: 500;
  color: #409EFF;
}

.log-card {
  margin-bottom: 20px;
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.log-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.author-name {
  font-weight: 500;
  font-size: 15px;
}

.log-date {
  font-size: 13px;
  color: #909399;
}

.log-actions {
  display: flex;
  gap: 8px;
}

.log-content {
  margin: 16px 0;
}

.content-section {
  margin-bottom: 20px;
}

.content-section:last-child {
  margin-bottom: 0;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
  margin-bottom: 12px;
  color: #303133;
}

.task-list {
  margin: 0;
  padding-left: 24px;
}

.task-list li {
  margin-bottom: 8px;
  color: #606266;
  line-height: 1.6;
}

.text-content {
  margin: 0;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 6px;
  color: #606266;
  line-height: 1.6;
}

.log-footer {
  display: flex;
  gap: 10px;
  margin-top: 12px;
}

.task-tags {
  margin-top: 8px;
}
</style>

